﻿using Mercury.Core.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Mercury.Core.Extensions
{
    public static class PropertyInfoExtensions
    {
        public static object GetDefaultValue(this PropertyInfo property)
        {
            object keyDefaultVal; 
            if (property.PropertyType == typeof(string))
                keyDefaultVal = default(string);
            else
                keyDefaultVal = property.PropertyType.Assembly.CreateInstance(property.PropertyType.FullName);//.ToString();
            return keyDefaultVal;
        }

        //private static string[] _createFields { get; set; }
        private static Dictionary<Type, List<string>> _createFields = new Dictionary<Type, List<string>>();
        public static List<string> CreateFields(this Type type)
        {
            if (_createFields.ContainsKey(type)) return _createFields[type];
            lock (_createFields)
            {
                if (_createFields.ContainsKey(type)) return _createFields[type];
                _createFields.Add(type, GetField(AppSetting.CreateMember, type));
            }
            return _createFields[type];
        }

        private static Dictionary<Type, List<string>> _modifyFields = new Dictionary<Type, List<string>>();
        public static List<string> ModifyFields(this Type type)
        {
            if (_modifyFields.ContainsKey(type)) return _modifyFields[type];
            lock (_modifyFields)
            {
                if (_modifyFields.ContainsKey(type)) return _modifyFields[type];
                _modifyFields.Add(type, GetField(AppSetting.ModifyMember, type));
            }
            return _modifyFields[type];
        }

        public static List<string> GetDeletionFileds(this Type type)
        {
            var deletionFlag = AppSetting.SoftDeletion;
            var detailType = type;
            var deleteProperty = detailType.GetProperty(AppSetting.DeletionFlagField);
            deletionFlag = deletionFlag && deleteProperty != null;
            var list = new List<string>();
            if (deletionFlag)
            {
                list.Add(deleteProperty.Name);
                list.AddRange(detailType.ModifyFields());
            }
            return list;
        }

            private static List<string> GetField(TableDefaultColumns columns, Type type)
        {
            var list = new List<string>();
            foreach (var item in type.GetProperties())
            {
                list.AddRange(columns.UserIdField.Where(c => c == item.Name));
                list.AddRange(columns.DateField.Where(c => c == item.Name));
                list.AddRange(columns.UserNameField.Where(c => c == item.Name));
            }
            return list;
        }
    }
}
